package com.xinghou.platform.service.main.impl;

import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.xinghou.platform.dao.bases.util.StringUtils;
import com.xinghou.platform.dao.main.NoticeDAO;
import com.xinghou.platform.dao.main.SharedCardDAO;
import com.xinghou.platform.dao.main.StoreDAO;
import com.xinghou.platform.entity.req.ListReq;
import com.xinghou.platform.model.main.Notice;
import com.xinghou.platform.model.main.NoticeTo;
import com.xinghou.platform.model.main.SharedCard;
import com.xinghou.platform.model.main.Store;
import com.xinghou.platform.server.api.bussiness.impl.JiGuangPushServiceImpl;
import com.xinghou.platform.server.api.log.LoggerFactory;
import com.xinghou.platform.service.main.NoticeService;
import com.xinghou.platform.util.JsonUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("NoticeService")
public class NoticeServiceImpl implements NoticeService {
    public static final String SYSTEM_MESSAGE_CODE = "10004";
    private Logger logError = LoggerFactory.getServerErrorLogger(NoticeServiceImpl.class);
    @Resource
    private NoticeDAO noticeDAO;

    @Resource
    private SharedCardDAO sharedCardDAO;

    @Resource
    private StoreDAO storeDAO;

    @Autowired
    JiGuangPushServiceImpl jiGuangPushService;


    @Override
    public List<Notice> list(ListReq listReq) {

        return noticeDAO.list(listReq);

    }


    @Override
    public boolean notice(Notice notice) {
        if (null == notice) {
            return false;
        }
        if ("2".equals(notice.getFrom()) &&
                (StringUtils.isNullOrEmpty(notice.getType()) ||
                StringUtils.isNullOrEmpty(String.valueOf(notice.getReceiverId())) ||
                StringUtils.isNullOrEmpty(notice.getMessagecode()) ||
                StringUtils.isNullOrEmpty(String.valueOf(notice.getFrom())))) {
            return false;
        }

        NoticeTo noticeTo = new NoticeTo();
        noticeTo.setPlatform(Integer.parseInt(notice.getPlatform()));
        noticeTo.setReceiverId(notice.getReceiverId());
        noticeTo.setJpushid(notice.getJpushid());
        noticeTo.setText(JsonUtil.toJson(notice.toJpushContent()));
        noticeTo.setContent(notice.getText());
        noticeTo.setTitle(notice.getTitle());
        noticeTo.setJumpNativePage(notice.getJumpNativePage());
        noticeTo.setJumpUrl(notice.getJumpUrl());
        noticeTo.setAttachId(notice.getAttachId());
        if(!StringUtils.isNullOrEmpty(notice.getType())){
            noticeTo.setType(Integer.parseInt(notice.getType()));
        }

        if (!StringUtils.isNullOrEmpty(notice.getPubTime())){
            noticeTo.setSchedule(JsonUtil.longToDate(Long.parseLong(notice.getPubTime())));
        }
        String jpushid = message(noticeTo);
        notice.setJpushid(jpushid);
        noticeDAO.saveNotice(notice);
        return true;

    }

    private String message(NoticeTo notice) {
        String jpushid ="";
        Platform platform = null;
        Audience audience;
        Message message;

        if (null == notice.getPlatform() || 0 == notice.getPlatform()) {
            platform = Platform.all();
        } else if (1 == notice.getPlatform()) {
            platform = Platform.android();
        } else if (2 == notice.getPlatform()) {
            platform = Platform.ios();
        } else {
            platform = Platform.all();
        }

        message = Message.newBuilder()
                .setMsgContent(StringUtils.isNullOrEmpty(notice.getText()) ? "{}" : notice.getText())
                .build();

        if (null == notice.getReceiverId() || StringUtils.isNullOrEmpty(notice.getReceiverId().toString())) {
            audience = Audience.all();
        } else {
            audience = Audience.alias(notice.getReceiverId().toString());
        }
        try {
            PushPayload pushPayload = null;
            if(notice.getType()!=null&&notice.getType()==2) {
                pushPayload = PushPayload.newBuilder()
                        .setPlatform(platform)
                        .setAudience(audience)
                        .setOptions(Options.newBuilder().setApnsProduction(true).build())
                        .setNotification(Notification.newBuilder()
                                .addPlatformNotification(IosNotification.newBuilder()
                                        .setAlert(notice.getContent())
                                        .addExtra("jumppage", notice.getJumpNativePage())
                                        .addExtra("jumpurl", notice.getJumpUrl())
                                        .addExtra("attachid", notice.getAttachId())
                                        .build())
                                .addPlatformNotification(AndroidNotification.newBuilder()
                                        .setAlert(notice.getContent())
                                        .addExtra("jumppage", notice.getJumpNativePage())
                                        .addExtra("jumpurl", notice.getJumpUrl())
                                        .addExtra("attachid", notice.getAttachId())
                                        .build())
                                .build())
                                .build();
                if (StringUtils.isNullOrEmpty(notice.getSchedule())) {
                    jpushid = jiGuangPushService.pushMessage(pushPayload);
                } else {
                    jpushid = jiGuangPushService.pushScheduleMessage(notice.getSchedule(), pushPayload);
                }
            } else {
                pushPayload = PushPayload.newBuilder()
                        .setPlatform(platform)
                        .setAudience(audience)
                        .setMessage(message)
                        .build();
                if(StringUtils.isNullOrEmpty(notice.getSchedule())){
                    jpushid = jiGuangPushService.pushMessage(pushPayload);
                }else{
                    jpushid = jiGuangPushService.pushScheduleMessage(notice.getSchedule(),pushPayload);
                }
            }



        } catch (Exception e) {
            e.printStackTrace();
            logError.error("jpush error is {}", e);
        }
        return jpushid;
    }

    private void push(Notice notice) {

    }

    @Override
    public void updateNotice(Notice notice) {

    }


    @Override
    public void removeNotice(String jpushid) {
        jiGuangPushService.removeScheduleMessage(jpushid);
        noticeDAO.deleteNotice(jpushid);
    }


    @Override
    public boolean cityNotice(Notice notice) {
        if (null == notice) {
            return false;
        }
        if  (StringUtils.isNullOrEmpty(notice.getAttachId())) {
            return false;
        }

        SharedCard sharedCard = sharedCardDAO.getSharedCardBycardId(Integer.parseInt(notice.getAttachId()));
        if(sharedCard==null){
            return false;
        }
        notice.setJumpNativePage("2");
        Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
        if(store==null||StringUtils.isNullOrEmpty(store.getAd_code())){
            return false;
        }
        notice.setCitypush("1");
        String ss =""+sharedCard.getDiscount()+"折"+store.getName()+"折扣卡,卡主等你来勾搭~";
        notice.setText(ss);
        String tagcode =store.getAd_code().substring(0,4)+"00";
        PushPayload pushPayload = PushPayload.newBuilder()
                    .setPlatform(Platform.all())
                            .setAudience(Audience.tag(tagcode))
                            .setOptions(Options.newBuilder().setApnsProduction(true).build())
                            .setNotification(Notification.newBuilder()
                                    .addPlatformNotification(IosNotification.newBuilder()
                                            .setAlert(notice.getText())
                                            .addExtra("jumppage", notice.getJumpNativePage())
                                            .addExtra("attachid", notice.getAttachId())
                                            .build())
                                    .addPlatformNotification(AndroidNotification.newBuilder()
                                            .setAlert(notice.getText())
                                            .addExtra("jumppage", notice.getJumpNativePage())
                                            .addExtra("attachid", notice.getAttachId())
                                            .build())
                                    .build())
                .build();
        String  jpushid = jiGuangPushService.pushMessage(pushPayload);
        notice.setJpushid(jpushid);
        noticeDAO.saveNotice(notice);
        return true;

    }
}
